package org.dromara.business.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.dromara.business.domain.Coupon;
import org.dromara.business.domain.Goods;
import org.dromara.business.domain.bo.GoodsBo;
import org.dromara.business.domain.vo.BusinessConfigVo;
import org.dromara.business.domain.vo.CouponVo;
import org.dromara.business.domain.vo.GoodsVo;
import org.dromara.business.mapper.GoodsMapper;
import org.dromara.business.service.BusinessConfigService;
import org.dromara.business.service.CouponService;
import org.dromara.business.service.GoodsService;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StreamUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.system.domain.SysUser;
import org.dromara.system.service.ISysUserService;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 商城商品Service业务层处理
 *
 * @author Lion Li
 * @date 2025-05-18
 */
@RequiredArgsConstructor
@Service
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements GoodsService {

    private final GoodsMapper baseMapper;
    private final ISysUserService userService;
    private final BusinessConfigService configService;
    private final CouponService couponService;

    /**
     * 查询商城商品
     */
    @Override
    public GoodsVo queryById(Long goodsId) {
        GoodsVo goodsVo = baseMapper.selectVoById(goodsId);
        this.setPrice(List.of(goodsVo));
        if (LoginHelper.isUser()) {
            List<Coupon> list = couponService.lambdaQuery().eq(Coupon::getCreateBy, LoginHelper.getUserId())
                .le(Coupon::getConditionAmount, goodsVo.getVipPrice())
                .eq(Coupon::getStatus, "0").list();
            goodsVo.setCouponVoList(BeanUtil.copyToList(list, CouponVo.class));
        }
        return goodsVo;
    }

    /**
     * 查询商城商品列表
     */
    @Override
    public TableDataInfo<GoodsVo> queryPageList(GoodsBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<Goods> lqw = buildQueryWrapper(bo);
        Page<GoodsVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        if (CollectionUtil.isNotEmpty(result.getRecords())) {
            this.setPrice(result.getRecords());
        }
        return TableDataInfo.build(result);
    }

    /**
     * 查询商城商品列表
     */
    @Override
    public List<GoodsVo> queryList(GoodsBo bo) {
        LambdaQueryWrapper<Goods> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<Goods> buildQueryWrapper(GoodsBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<Goods> lqw = Wrappers.lambdaQuery();
        lqw.like(StrUtil.isNotBlank(bo.getName()), Goods::getName, bo.getName());
        lqw.eq(StrUtil.isNotBlank(bo.getUrl()), Goods::getUrl, bo.getUrl());
        lqw.eq(bo.getPrice() != null, Goods::getPrice, bo.getPrice());
        lqw.eq(StrUtil.isNotBlank(bo.getStatus()), Goods::getStatus, bo.getStatus());
        lqw.eq(StrUtil.isNotBlank(bo.getInfo()), Goods::getInfo, bo.getInfo());
        lqw.eq(StrUtil.isNotBlank(bo.getInfoDesc()), Goods::getInfoDesc, bo.getInfoDesc());
        lqw.eq(bo.getNum() != null, Goods::getNum, bo.getNum());
        lqw.eq(StrUtil.isNotBlank(bo.getType()), Goods::getType, bo.getType());
        lqw.eq(StrUtil.isNotBlank(bo.getOneType()), Goods::getOneType, bo.getOneType());
        if (LoginHelper.isUser()) {
            lqw.eq(Goods::getStatus, "0");
        }
        lqw.orderByDesc(Goods::getNum);
        return lqw;
    }

    /**
     * 新增商城商品
     */
    @Override
    public Boolean insertByBo(GoodsBo bo) {
        Goods add = MapstructUtils.convert(bo, Goods.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setGoodsId(add.getGoodsId());
        }
        return flag;
    }

    /**
     * 修改商城商品
     */
    @Override
    public Boolean updateByBo(GoodsBo bo) {
        Goods update = MapstructUtils.convert(bo, Goods.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(Goods entity) {

    }

    /**
     * 批量删除商城商品
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {

        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public void setPrice(List<GoodsVo> goodsMallList) {
        if (!LoginHelper.isLogin() || !LoginHelper.isUser()) {
            return;
        }
        if (CollectionUtil.isEmpty(goodsMallList)) {
            return;
        }

        List<BusinessConfigVo> vipList = configService.queryByKey("vip");
        Map<Integer, String> map = StreamUtils.toMap(vipList, BusinessConfigVo::getSortNo, t -> t.getRemark().split("-")[1]);
        SysUser user = userService.lambdaQuery().select(SysUser::getVip)
            .eq(SysUser::getUserId, LoginHelper.getUserId()).one();
        goodsMallList.forEach(item -> item.setVipPrice(new BigDecimal(map.get(user.getVip())).multiply(item.getPrice())));
    }
}
